package cn.infrabase.token;

import cn.infrabase.Errors;
import cn.infrabase.Gid;

import javax.annotation.Nullable;

import java.util.Map;

/**
 * @author Weimin Gao
 * @since 1.0.0
 **/
public class JwtTokenService extends BaseTokenService {

	/**
	 * 构造函数。
	 *
	 * @param properties 令牌生成配置。
	 */
	public <P extends TokenProperties> JwtTokenService(P properties) {
		super(properties);
	}

	@Override
	public Token generate(@Nullable Long efftime, @Nullable Gid tid, @Nullable Map<String,String> data) throws TokenException {
		String algo = getTokenProperties().getAlgorithm().code();
		byte[] key = getTokenProperties().key();
		long time = efftime == null ? getTokenProperties().getEfftime() : efftime;
		return JwtUtils.generate(algo, key, time, tid, data);
	}

	@Override
	public Token parse(String token) throws TokenException {
		return JwtUtils.parse(token, getTokenProperties().key());
	}

	@Override
	public Token refresh(String token, @Nullable Map<String,String> data) throws TokenException {
		try {
			Token jwt = parse(token);
			long efftime = jwt.getEfftime();
			return generate(efftime, Gid.of(jwt.getTid()), data == null ? jwt.getData() : data);
		} catch (TokenException cause) {
			throw cause;
		} catch (Exception cause) {
			throw new TokenException(cause, Errors.REFRESH_TOKEN_EXPIRED);
		}
	}
}
